import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../Services/api_service.dart';
import '../../base/base_widget.dart';
import '../../model/system_tree_model.dart';
import '../../util/utils.dart';
import 'knowledge_content.dart';

class KnowledgePage extends BaseWidget {
  @override
  BaseWidgetState<BaseWidget> getState() {
    return KnowledgePageState();
  }
}

class KnowledgePageState extends BaseWidgetState<KnowledgePage> {
  final List<SystemTreeData> _systemTreeDataList = [];
  //listview控制器
  final ScrollController _scrollController = ScrollController();
  bool showToTopBtn = false; //是否显示“返回到顶部”按钮

  @override
  void initState() {
    super.initState();
    setAppBarVisible(false);

    _getData();

    _scrollController.addListener(() {
      if (_scrollController.offset < 200 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_scrollController.offset >= 200 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  Future<Null> _getData() async {
    ApiService().getSystemTree((SystemTreeModel systemTreeModel) {
      if (systemTreeModel.errorCode == 0) {
        int count = systemTreeModel.data?.length ?? 0;
        if (count > 0) {
          showContent();
          setState(() {
            _systemTreeDataList.clear();
            _systemTreeDataList.addAll(systemTreeModel.data!);
          });
        } else {
          showEmpty();
        }
      } else {
        Fluttertoast.showToast(msg: systemTreeModel.errorMsg ?? "err");
      }
    },(DioError error) {
      showError();
    });
  }

  Widget? _renderRow(BuildContext context, int index) {
    if (index < _systemTreeDataList.length) {
      return InkWell(
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return KnowledgeContentPage(data: _systemTreeDataList[index]);
            }));
          },
          child: Container(
            color: Colors.white,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Expanded(
                    child: Container(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: const EdgeInsets.only(bottom: 8),
                            child: Text(
                              _systemTreeDataList[index].name ?? "",
                              style: const TextStyle(
                                  fontSize: 16,
                                  color: Color(0xFF3D4E5F),
                                  fontWeight: FontWeight.bold),
                              textAlign: TextAlign.left,
                            ),
                          ),
                          Container(
                              alignment: Alignment.centerLeft,
                              child: buildChildren(index, _systemTreeDataList[index].children ?? [])),
                        ],
                      ),
                    )),
                const Icon(Icons.chevron_right)
              ],
            ),
          ));
    }
    return null;
  }

  Widget buildChildren(int index, List<SystemTreeChild> systemTreeChildList) {
    List<Widget> tiles = [];
    Widget content;
    for (int i = 0; i < systemTreeChildList.length; i++) {
      SystemTreeChild item = systemTreeChildList[i];
      tiles.add(
        GestureDetector(
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return KnowledgeContentPage(data: _systemTreeDataList[index], selectedIndex: i);
            }));
          },
          child: Chip(
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            backgroundColor: Utils.getChipBgColor(item.name ?? ""),
            label: Text(item.name ?? ""),
            side: BorderSide.none,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          ),
        )
      );
    }

    content = Wrap(
        spacing: 12,
        runSpacing: 12,
        alignment: WrapAlignment.start,
        children: tiles);

    return content;
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  AppBar getAppBar() {
    return AppBar(
      title: const Text("不显示"),
    );
  }

  @override
  Widget getContentWidget(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        displacement: 15,
        onRefresh: _getData,
        child: ListView.separated(
          itemBuilder: _renderRow,
          physics: const AlwaysScrollableScrollPhysics(),
          separatorBuilder: (BuildContext context, int index) {
            return Container(
              height: 0.5,
              color: Colors.black26,
            );
          },
          itemCount: _systemTreeDataList.length,
          controller: _scrollController,
        ),
      ),
      floatingActionButton: !showToTopBtn ? null : FloatingActionButton(
          child: const Icon(Icons.arrow_upward),
          onPressed: () {
            _scrollController.animateTo(.0,
                duration: const Duration(milliseconds: 200),
                curve: Curves.ease
            );
          }
      ),
    );
  }

  @override
  void onClickErrorWidget() {
    showLoading();
    _getData();
  }

}
